<template>
  <div class="categories">
    <el-card>
      <el-button type="primary" @click="showAdd">添加分类</el-button>
      <el-table
        :data="categoriesList"
        row-key="cat_id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        max-height="600px"
        border
        style="width: 100%; margin: 10px 0"
      >
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column prop="cat_name" label="分类名称"></el-table-column>
        <el-table-column label="是否有效">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.cat_deleted"
              size="mini"
              type="success"
              icon="el-icon-check"
              circle
            ></el-button>
            <el-button
              v-else
              size="mini"
              type="danger"
              icon="el-icon-close"
              circle
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="排序">
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.cat_pid == 0
                  ? ''
                  : scope.row.cat_pid == 1
                  ? 'success'
                  : 'warning'
              "
              effect="dark"
            >
              {{ scope.row.cat_pid | filLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              @click="showEdit(scope.row)"
              size="mini"
              type="primary"
              icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button
              @click="delCategoriesForm(scope.row)"
              size="mini"
              type="danger"
              icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageObj.pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 编辑 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form ref="editForm" :model="editForm">
        <el-form-item
          prop="cat_name"
          label="分类名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCategoriesForm()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 添加 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form ref="addForm" :model="addForm" :rules="rules">
        <el-form-item
          prop="cat_name"
          label="分类名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" :label-width="formLabelWidth">
          <el-cascader
            clearable
            :options="allCategoriesList"
            :props="{
              checkStrictly: true,
              expandTrigger: 'hover',
              label: 'cat_name',
              value: 'cat_id',
            }"
            @change="addChange"
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategoriesForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getCategories,
  getEditCategories,
  getDelCategories,
  getAddCategories,
} from "@/api/index";
export default {
  data() {
    return {
      categoriesList: [],
      allCategoriesList: [],
      total: 0,
      pageObj: {
        type: [1, 2, 3],
        pagenum: 1,
        pagesize: 5,
      },
      editForm: {
        cat_id: "",
        cat_name: "",
      },
      addForm: {
        //默认空一级分类
        cat_pid: 0,
        cat_name: "",
        cat_level: "",
      },
      rules: {
        cat_name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
          {
            min: 1,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      delDialogFormVisible: false,
      formLabelWidth: "120px",
    };
  },
  created() {
    this.getCategoriesData();
    this.getAllCategoriesData();
  },
  methods: {
    //添加分类弹出框
    showAdd() {
      this.addDialogFormVisible = true;
      this.addForm.cat_level = 0;
      this.addForm.cat_pid = 0;
    },
    // 添加分类
    async addCategoriesForm() {
      try {
        let success = await this.$refs["addForm"].validate();
        if (!success) return false;
        let {
          meta: { msg, status },
        } = await getAddCategories(this.addForm);
        console.log(msg, status)
        status == 201 ? this.$message.success(msg) : this.$message.error(msg);
        this.getCategoriesData();
        this.addDialogFormVisible = false;
      } catch (error) {
        console.log(error);
      }
    },
    // 添加下拉框
    addChange(val) {
      this.addForm.cat_pid = val[val.length - 1];
      if (val.length == 1) return (this.addForm.cat_level = 1);
      if (val.length == 2) return (this.addForm.cat_level = 2);
    },
    //编辑分类弹出框
    showEdit(form) {
      this.editDialogFormVisible = true;
      this.editForm.cat_id = form.cat_id;
      this.editForm.cat_name = form.cat_name;
    },
    //编辑分类名
    async editCategoriesForm() {
      let {
        meta: { msg, status },
      } = await getEditCategories(this.editForm);
      status == 200 ? this.$message.success(msg) : this.$message.warning(msg);
      this.getCategoriesData();
      this.editDialogFormVisible = false;
    },
    // 删除分类
    async delCategoriesForm(form) {
      this.editForm.cat_id = form.cat_id;
      console.log(form.cat_id);
      let res = await this.$confirm(
        "此操作将删除该商品分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (!res) return this.$message("取消删除");
      let {
        meta: { msg, status },
      } = await getDelCategories(this.editForm);
      console.log(msg, status);
      status == 200 ? this.$message.success(msg) : this.$message.warning(msg);
      this.getCategoriesData();
      this.delDialogFormVisible = false;
    },
    //分页
    handleSizeChange(val) {
      this.total = val;
      this.getCategoriesData();
    },
    handleCurrentChange(val) {
      this.pageObj.pagenum = val;
      this.getCategoriesData();
    },
    // 获取商品分类
    async getCategoriesData() {
      let {
        data: { result, total },
        meta: { msg, status },
      } = await getCategories(this.pageObj);
      if (status != 200) return this.$message.error(msg);
      this.categoriesList = result;
      this.total = total;
    },
    async getAllCategoriesData() {
      let {
        data,
        meta: { msg, status },
      } = await getCategories();
      if (status != 200) return this.$message.error(msg);
      this.allCategoriesList = this.getChildren(data);
    },
    getChildren(arr) {
      let newarr = [];
      arr.forEach((item) => {
        // console.log(item.cat_pid != 0)
        if (item.children == undefined&& item.cat_level==2) return;
        let obj={
          cat_name: item.cat_name,
          cat_pid: item.cat_pid,
          cat_level: item.cat_level,
          cat_id: item.cat_id,
          // children: this.getChildren(item.children),
        }
        if(item.children != undefined) obj.children=this.getChildren(item.children)
        if(item.children != undefined&&obj.children.length==0) delete obj.children
        newarr.push(obj);
      });
      return newarr;
    },
  },
  filters: {
    filLevel(level) {
      if (level == 0) return "一级";
      if (level == 1) return "二级";
      return "三级";
    },
  },
};
</script>